package UI;

import SocketClient.Client;
import SocketClient.ClientVideo;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.*;

public class Main_UI {
    public static final int screenWidth= Toolkit.getDefaultToolkit().getScreenSize().width;
    public static final int screenHeight=Toolkit.getDefaultToolkit().getScreenSize().height;
    public static final int windowWidth=980;
    public static final int windowHeight=760;
    JFrame jFrame=new JFrame("用户发卡端管理系统");
    String host;
    int port;
    String username;
    String tell;
    String cardId;
    String userID;
    String address;
    Client client;
    JLabel usernameJLabel=new JLabel("姓              名：");
    JTextField usernameJTe=new JTextField(20);
    JLabel printMessageJLabel=new JLabel("全 局 打 印：");
    JLabel printWindow=new JLabel();
    JLabel tellJLabel=new JLabel("电              话：");
    JTextField tellJTe=new JTextField(20);
    JLabel addressJLabel=new JLabel("住            址：");
    JTextField addreddJTe=new JTextField(20);
    JLabel cardJLabel=new JLabel("卡              号：");
    JLabel cardJta=new JLabel();
    JLabel idJLabel=new JLabel("身 份 证 号：");
    JTextField idJTe=new JTextField(20);
    JLabel hostJLabel=new JLabel("服务器IP地址：");
    JTextField hostJTe=new JTextField(20);
    JLabel portJLabel=new JLabel("服务器端口：");
    JTextField portJTe=new JTextField(20);
    JButton connectBtn=new JButton("连接服务器");
    JButton readBtn=new JButton("读卡");
    JButton fingerBtn=new JButton("读指纹");
    JButton getVideoBtn=new JButton("获取摄像头数据");
    JButton photoBtn=new JButton("拍照");
    //JButton modifyBtn=new JButton("修改用户数据");
    JButton staticsBtn=new JButton("用户数据统计");
    JButton makeCardBtn=new JButton("卡片制作");
    JButton closeBtn=new JButton("关闭服务器连接");
    JOptionPane OptionPane=new JOptionPane();//确认用户信息提示框
    public void init() throws Exception{
        //BufferedImage image=ImageIO.read(new File("img/IMG_20210507_203807.jpg"));
        BufferedImage image=null;
        MyBackGroudJpanel backGroudJpanel=new MyBackGroudJpanel(ImageIO.read(new File("img/library.jpg")));
        jFrame.setIconImage(ImageIO.read(new File("img/userManage.png")));
        MyVideoCanvas videoCanvas=new MyVideoCanvas();
        videoCanvas.setPreferredSize(new Dimension(640,480));
        videoCanvas.setBorder(BorderFactory.createLineBorder(Color.RED,5));
        cardJta.setPreferredSize(new Dimension(205,12));
        cardJta.setBorder(BorderFactory.createLineBorder(Color.white,1));
        cardJta.setText(" ");
        printWindow.setPreferredSize(new Dimension(205,12));
        printWindow.setBorder(BorderFactory.createLineBorder(Color.white,1));
        printWindow.setText(" ");
        usernameJTe.setPreferredSize(new Dimension(205,12));
        addreddJTe.setPreferredSize(new Dimension(205,12));
        idJTe.setPreferredSize(new Dimension(205,12));
        hostJTe.setText("192.168.1.100");
        portJTe.setText("8888");
        //用户姓名和消息组装
        Box userBox = Box.createHorizontalBox();
        userBox.add(usernameJLabel);
        userBox.add(Box.createHorizontalStrut(20));
        userBox.add(usernameJTe);
        userBox.add(Box.createHorizontalStrut(20));
        userBox.add(printMessageJLabel);
        userBox.add(Box.createHorizontalStrut(20));
        userBox.add(printWindow);
        //组装电话和地址

        Box tellBox=Box.createHorizontalBox();
        tellBox.add(tellJLabel);
        tellBox.add(Box.createHorizontalStrut(20));
        tellBox.add(tellJTe);
        tellBox.add(Box.createHorizontalStrut(20));
        tellBox.add(addressJLabel);
        tellBox.add(Box.createHorizontalStrut(20));
        tellBox.add(addreddJTe);

        //组装卡号和身份证号
        Box idBox=Box.createHorizontalBox();
        idBox.add(cardJLabel);
        idBox.add(Box.createHorizontalStrut(20));
        idBox.add(cardJta);
        idBox.add(Box.createHorizontalStrut(20));
        idBox.add(idJLabel);
        idBox.add(Box.createHorizontalStrut(20));
        idBox.add(idJTe);
        Box serverBox= Box.createHorizontalBox();
        serverBox.add(hostJLabel);
        serverBox.add(Box.createHorizontalStrut(20));
        serverBox.add(hostJTe);
        serverBox.add(Box.createHorizontalStrut(20));
        serverBox.add(portJLabel);
        serverBox.add(Box.createHorizontalStrut(20));
        serverBox.add(portJTe);

        JPanel bottomPanel=new JPanel();
        bottomPanel.add(connectBtn);
        bottomPanel.add(fingerBtn);
        bottomPanel.add(readBtn);
        //bottomPanel.add(modifyBtn);
        bottomPanel.add(staticsBtn);
        bottomPanel.add(getVideoBtn);
        bottomPanel.add(photoBtn);
        bottomPanel.add(makeCardBtn);
        bottomPanel.add(closeBtn);
        //为按钮添加事件
        connectBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                host=hostJTe.getText();
                port=Integer.valueOf(portJTe.getText());
                client=new Client(host,port);
                boolean isConnected = client.Connect();
                if(isConnected){
                    printWindow.setText("服务器连接成功！");
                }else{
                    printWindow.setText("服务器连接失败！");
                }

            }
        });



        readBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    cardId=client.OptionReadCard();
                    if(cardId !=null){
                        cardJta.setText(cardId);
                        printWindow.setText("读卡成功！");
                    }else{
                        printWindow.setText("读卡失败！");
                    }
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        });

        fingerBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    boolean isReadFinger = client.Operation("readFinger");
                    if(isReadFinger){
                        printWindow.setText("读取指纹成功！");
                    }else{
                        printWindow.setText("读取指纹失败！");
                    }
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        });

        photoBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    boolean isPhoto = client.Operation("photo");
                    if(isPhoto){
                        printWindow.setText("创建人脸特征成功！");
                    }else{
                        printWindow.setText("创建人脸特征失败！");
                    }
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        });

        makeCardBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                username=usernameJTe.getText();
                tell=tellJTe.getText();
                address=addreddJTe.getText();
                cardId=cardJta.getText();
                userID=idJTe.getText();
                if(username.equals("")||tell.equals("")||address.equals("")||cardId.equals("")||userID.equals("")){
                    OptionPane.showMessageDialog(jFrame, "尚有用户信息未填写", "用户信息确认", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                try {
                    Class.forName("com.mysql.cj.jdbc.Driver");
                    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/project1.1", "root", "jjbone");
                    String sql="insert into user(username,tellnum,address,cardnum,userid) values (?, ?, ?, ?,?)" ;

                    PreparedStatement pst = conn.prepareStatement(sql);
                    pst.setString(1,username);
                    pst.setString(2,tell);
                    pst.setString(3,address);
                    pst.setString(4,cardId);
                    pst.setString(5,userID);
                    int resultRow = pst.executeUpdate();
                    if(resultRow>0){
                        try {
                            String sql2="select id from user where user.userid=?";
                            pst=conn.prepareStatement(sql2);
                            pst.setString(1,userID);
                            ResultSet rst = pst.executeQuery();
                            int idSequence=0;
                            if(rst.next()){
                                idSequence=rst.getInt(1);
                                boolean isMakeCard = client.makeCard(idSequence);
                                if(isMakeCard){
                                    printWindow.setText("发卡成功！");
                                }else{
                                    printWindow.setText("发卡失败！");
                                }
                            }else{
                                printWindow.setText("发卡失败！");
                            }
                            rst.close();
                            pst.close();
                            conn.close();
                        } catch (IOException ioException) {
                            ioException.printStackTrace();
                        }
                    }else{
                        printWindow.setText("发卡失败！");
                    }
                } catch (ClassNotFoundException | SQLException classNotFoundException) {
                    classNotFoundException.printStackTrace();
                }



            }
        });

        closeBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    boolean b = client.disConnect();
                    if(b){
                        printWindow.setText("断开服务器连接成功！");
                    }else{
                        printWindow.setText("断开服务器连接失败！");
                    }
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        });

//        modifyBtn.addActionListener(new ActionListener() {
//            @Override
//            public void actionPerformed(ActionEvent e) {
//                new ModifyUserinfor_UI(jFrame).init();
//            }
//        });

        staticsBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Statistics_UI(jFrame).init();
            }
        });

        getVideoBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    boolean isGetVideo = client.Operation("getVideo");
                    if(isGetVideo){
                        printWindow.setText("视频即将到来！");
                    }else{
                        printWindow.setText("视频获取失败！");
                    }
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }

                new Thread(){
                    @Override
                    public void run() {
                        ClientVideo clientVideo = new ClientVideo(port,host,videoCanvas);
                        try {
                            clientVideo.init();
                        } catch (IOException ioException) {
                            ioException.printStackTrace();
                        }
                    }
                }.start();
            }
        });
        //组装右侧的所有
        Box rightBox=Box.createVerticalBox();
        rightBox.add(Box.createVerticalStrut(15));
        rightBox.add(userBox);
        rightBox.add(Box.createVerticalStrut(15));
        rightBox.add(tellBox);
        rightBox.add(Box.createVerticalStrut(15));
        rightBox.add(idBox);
        rightBox.add(Box.createVerticalStrut(15));
        rightBox.add(serverBox);
        rightBox.add(Box.createVerticalStrut(15));
        //组装全部的
        backGroudJpanel.setLayout(new FlowLayout());
        backGroudJpanel.add(videoCanvas);
        backGroudJpanel.add(rightBox);





        jFrame.add(bottomPanel,BorderLayout.SOUTH);
        jFrame.add(backGroudJpanel);
        jFrame.pack();
        jFrame.setResizable(false);
        jFrame.setBounds((screenWidth-windowWidth)/2,(screenHeight-windowHeight)/2,windowWidth,windowHeight);
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        jFrame.setVisible(true);

    }
}
